package k6_exam;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 有一个ArrayList集合，集合中的元素分别{1,2,3,6,8,7,7,8,2,2,1,2},将重复的数字找到
 * 并按数字的大小排序输出输出，格式是
 * 1:2次
 * 2:4次
 * 3:1次
 * 6:1次
 * 7:3次
 * 8:2次
 */
public class NumsDistinct {

    public static void method1(List<Integer> nums){

        TreeMap<Integer,Integer> numMap = new TreeMap<>();

        for (Integer num : nums) {
            if(numMap.containsKey(num)){
                numMap.put(num,numMap.get(num)+1);
            }else{
                numMap.put(num,1);
            }
        }

        for (Map.Entry<Integer, Integer> entry : numMap.entrySet()) {
            System.out.println(entry.getKey()+":"+ entry.getValue()+"次");
        }
    }

    public static void method2(List<Integer> nums){

        Collections.sort(nums);
        String numStr = nums.toString().replaceAll(", |\\[|\\]","");

        String tmp = "";
        int strLength = 0;
        while(numStr.length()>0){
            //原字符串长度
            strLength = numStr.length();
            tmp = String.valueOf(numStr.charAt(0));
            //替换掉首字符后的字符串
            numStr = numStr.replace(tmp,"");

            //当前字符的个数=原字符串长度-剩余字符的长度
            int length = strLength-numStr.length();

            System.out.println(tmp+":"+length+"次");
        }
    }

    public static void method3(List<Integer> nums){

        String numStr = nums.toString().replaceAll(", |\\[|\\]","");

        List<Integer> numList = nums.stream()
            .distinct()
            .sorted()
            .collect(Collectors.toList());

        int length;
        for (Integer num : numList) {
            length = numStr.length();
            numStr = numStr.replace(num+"","");
            System.out.println(num+":"+(length-numStr.length())+"次");
        }

    }


    public static void main(String[] args) {

        List<Integer> nums = Arrays.asList(1,2,3,6,8,7,7,8,2,2,1,2);

        method3(nums);

    }
}
